import UIKit
import JRTimer

public protocol JRNetworkSpeedManagerDelegate: NSObjectProtocol {
    func manger(update down: Double, up: Double)
}

public class JRNetworkSpeedManager: NSObject {
    
    private static var lastI: UInt32 = 0
    private static var lastO: UInt32 = 0
    
    public weak var delegate: JRNetworkSpeedManagerDelegate!
    
    private override init() { }
    
    public static let share: JRNetworkSpeedManager = {
        let instance = JRNetworkSpeedManager()
        
        let timer = Timer.JREvery(1.JRSeconds, { [weak instance] _ in
            instance?.getMomentNetworkAllValue()
        })
        return instance
    }()
    
    private func getMomentNetworkAllValue() {
        guard let model = JRNetworkSpeedHelper.getInterfaceBytes() else { return }
        calculate(speedBy: model)
    }
    
    private func calculate(speedBy model: JRNetworkSpeedModel) {
        let i: Double = Double(model.iValue - JRNetworkSpeedManager.lastI)
        let o: Double = Double(model.oValue - JRNetworkSpeedManager.lastO)
        JRNetworkSpeedManager.lastI = model.iValue
        JRNetworkSpeedManager.lastO = model.oValue
//        print("下行:", i / 1024)
//        print("上行:", o / 1024)
//        print("============================")
        delegate?.manger(update: i / 1024, up: o / 1024)
    }
}
